 #define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    bool row[9][10];
    bool col[9][10];
    bool grid[3][3][10];

    void solveSudoku(vector<vector<char>>& board) {
        //1.将board已经填入的数初始化到对应hash中
        for (int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 9; j++)
            {
                if (board[i][j] != '.')
                {
                    int num = board[i][j] - '0';
                    row[i][num] = col[j][num] = grid[i / 3][j / 3][num] = true;
                }
            }
        }

        dfs(board);
    }

    bool dfs(vector<vector<char>>& board)
    {
        for (int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 9; j++)
            {
                if (board[i][j] == '.')
                {
                    //填数
                    for (int num = 1; num <= 9; num++)
                    {
                        if (!row[i][num] && !col[j][num] && !grid[i / 3][j / 3][num])
                        {
                            board[i][j] = num + '0';
                            row[i][num] = col[j][num] = grid[i / 3][j / 3][num] = true;

                            //这时候说明这个数已经填充过，不用在重复填写，直接返回
                            if (dfs(board) == true) return true;

                            //恢复现场
                            board[i][j] = '.';
                            row[i][num] = col[j][num] = grid[i / 3][j / 3][num] = false;
                        }
                    }
                    //这里表示这个位置1~9都试过了，都不能满足条件，直接返回false
                    return false;
                }
            }
        }
        //全部遍历完，并且都填充完毕之后，直接返回即可
        return true;
    }
};

class Solution {
public:
    int m, n;
    bool vis[7][7];

    bool exist(vector<vector<char>>& board, string word) {
        m = board.size(), n = board[0].size();
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
            {
                if (board[i][j] == word[0])
                {
                    vis[i][j] = true;
                    //按照这个向下寻找，看是否满足单词
                    if (dfs(board, word, i, j, 1) == true) return true;
                    //恢复现场
                    vis[i][j] = false;
                }
            }
        //找过board中所有的字符都没找到word
        return false;
    }

    int dx[4] = { 0, 0, -1, 1 };
    int dy[4] = { 1, -1, 0, 0 };

    bool dfs(vector<vector<char>>& board, string& word, int i, int j, int pos)
    {
        if (pos == word.size()) return true;

        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && board[x][y] == word[pos])
            {
                vis[x][y] = true;
                if (dfs(board, word, x, y, pos + 1)) return true;
                vis[x][y] = false;
            }
        }
        //遍历所有位置都没找到符合条件的位置
        return false;
    }

};